package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.User;
import com.hanserwei.community.entity.request.user.*;
import com.hanserwei.community.entity.vo.UserVO;
import com.hanserwei.community.exception.ApiException;
import com.hanserwei.community.manager.OssManager;
import com.hanserwei.community.mapper.UserMapper;
import com.hanserwei.community.service.UserService;
import com.hanserwei.community.uitils.ThrowUtils;
import com.hanserwei.community.enums.ResponseCodeEnum;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final OssManager ossManager;

    @Override
    public UserVO userLogin(@NotNull UserLoginRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        // md5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        queryWrapper.eq("password", md5Password);
        User user = this.getBaseMapper().selectOne(queryWrapper);
        ThrowUtils.throwIf(user == null, ResponseCodeEnum.USER_ACCOUNT_ERROR, "用户账户错误");
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public UserVO userRegister(@NotNull UserRegisterRequest request) {
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new ApiException(ResponseCodeEnum.USER_PASSWORD_ERROR, "密码不一致");
        }
        // 拷贝属性
        User user = new User();
        BeanUtils.copyProperties(request, user);
        // 用户名正则：3-16位，只能包含字母数字下划线
        String usernameRegex = "^[a-zA-Z0-9_]{3,16}$";
        // 密码正则：6-15位任意字符
        String passwordRegex = "^.{6,15}$";
        if (user.getUserName() == null || !user.getUserName().matches(usernameRegex)) {
            throw new ApiException(ResponseCodeEnum.USER_ACCOUNT_ERROR, "用户名必须是3-16位字母、数字或下划线");
        }
        if (user.getPassword() == null || !user.getPassword().matches(passwordRegex)) {
            throw new ApiException(ResponseCodeEnum.USER_PASSWORD_ERROR, "密码必须是6-15位任意字符");
        }
        // 加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        boolean saved = this.save(user);
        ThrowUtils.throwIf(!saved, ResponseCodeEnum.SYSTEM_ERROR, "用户注册失败");
        // 返回 VO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public Page<User> queryUserByPage(UserQueryRequest request) {
        Page<User> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(request.getUserName() != null, "user_name", request.getUserName());
        queryWrapper.eq(request.getType() != null, "type", request.getType());
        queryWrapper.like(request.getRemarks() != null, "remarks", request.getRemarks());
        return this.page(page, queryWrapper);
    }

    @Override
    public User addUser(UserAddRequest request) {
        User user = new User();
        BeanUtils.copyProperties(request, user);
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        boolean saved = this.save(user);
        ThrowUtils.throwIf(!saved, ResponseCodeEnum.SYSTEM_ERROR, "用户添加失败");
        return user;
    }


    @Override
    public boolean updateUser(UserUpdateRequest request, Integer id) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        // 查询是否存在
        User user = getById(id);
        ThrowUtils.throwIf(user == null, ResponseCodeEnum.USER_NOT_FOUND, "用户不存在！");
        String userName = request.getUserName();
        Integer type = request.getType();
        String remarks = request.getRemarks();
        if (userName != null) {
            user.setUserName(userName);
        }
        if (type != null) {
            user.setType(type);
        }
        if (remarks != null) {
            user.setRemarks(remarks);
        }
        MultipartFile avatar = request.getAvatar();
        File destinationFile = null;
        try {
            // 获取原始文件名
            String originalFilename = avatar.getOriginalFilename();
            // 防止原始文件名为空
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 拼接目标文件路径
            destinationFile = Path.of(System.getProperty("user.dir"), id + extension).toFile();
            avatar.transferTo(destinationFile);
            // 上传头像
            String filePath = "avatar/" + id;
            String avatarUrl = ossManager.uploadFile(filePath, destinationFile);
            user.setAvatar(avatarUrl);
        } catch (Exception e) {
            throw new ApiException(ResponseCodeEnum.SYSTEM_ERROR, "上传头像失败！");
        } finally {
            if (destinationFile != null) {
                boolean deleted = destinationFile.delete();
                ThrowUtils.throwIf(!deleted, ResponseCodeEnum.SYSTEM_ERROR, "删除临时文件失败！");
            }
        }
        boolean updated = updateById(user);
        ThrowUtils.throwIf(!updated, ResponseCodeEnum.SYSTEM_ERROR, "用户更新失败！");
        return true;
    }
}
